/**
 * 绘制canvas曲线的类
 */

import { calcFx } from '@/utils/myMath'
import { AbstractCanvas } from './AbstractCanvas'

export class CurveCanvas extends AbstractCanvas {
  constructor(
    private canvas: HTMLCanvasElement,
    protected ctx: CanvasRenderingContext2D,
    private width: number,
    private height: number,
    private startY: number,
    private margin: number,
    private lst_config: CurveConfig[], // private scaleXY: [scaleX: number, scaleY: number],
  ) {
    super(ctx)
    this.init()
    this.draw()
  }

  // 初始化
  init() {
    this.ctx = this.canvas.getContext('2d')!
    this.canvas.width = this.width
    this.canvas.height = this.height
    // 修改坐标原点 将坐标原点移动至画布的左下角
    this.ctx.translate(this.margin, this.height - this.margin)
    this.ctx.translate(0, this.startY)
    // 翻转坐标轴 使坐标轴朝上
    this.ctx.scale(1, -1)
  }

  // 绘制曲线
  draw() {
    this.lst_config.forEach((config) => {
      const { towerPoint } = config
      const curvePoints = this.calcSingleCurvePoints(config)
      this.drawSingleCurve(towerPoint, curvePoints)
    })
  }

  // 计算单个区段的曲线点坐标
  private calcSingleCurvePoints(config: CurveConfig) {
    const { btSpan, Hi, h, w } = config
    const lst_point = [] as [x: number, y: number][]

    // 计算曲线点的坐标
    for (let m = 0; m < 50; m++) {
      const x = (config.btSpan / 49) * m
      const fx = calcFx({ H: Hi, w, x, l: btSpan, h })
      const y = (x * h) / btSpan - fx // 应该计算完成后为负值
      lst_point.push([x / 5, y * 2])
    }
    return lst_point
  }

  private drawSingleCurve(towerPoint: { x0: number; y0: number }, points: [x: number, y: number][]) {
    // 绘制曲线
    this.ctx.save()
    const { x0, y0 } = towerPoint
    this.ctx.translate(x0 / 5, y0 * 2)
    super.drawPolyline(points, 'red', 1)
    this.ctx.restore()
  }
}
